import { exec, execSync } from "child_process";

let url = `https://gitee.com/ZvmiY/PanelDrawing-API-document`; //项目地址可自行更改
let Path = `./resources/PanelDrawing-API/`; //存放位置
let cmd = "";

export class marry_GuGuNiu extends plugin {
    constructor() {
        super({
            name: '下载替换文件',
            dsc: '下载安装替换文件',
            event: 'message',
            priority: -1000,
            rule: [
                {
                    reg: /^#下载替换$/,
                    fnc: 'download_GuGuNiu',
                    permission: "master"
                },
                {
                    reg: /^#(强制)?更新替换$/,
                    fnc: 'update_GuGuNiu',
                    permission: "master"
                },
                {
                    reg: /^#启用替换$/,
                    fnc: 'apply_GuGuNiu',
                    permission: "master"
                }
            ]
        });
    }

    async download_GuGuNiu(e) {
        await e.reply(`开始下载${url}`);
        cmd = `git clone --depth=1 ${url} ${Path}`;
        exec(cmd, { cwd: process.cwd(), stdio: 'inherit' }, (error) => {
            if (error) return e.reply(`下载错误：\n${error}`);
            else { e.reply(`下载完成`); this.apply_GuGuNiu(e); }
        });

        await e.reply(`下载中，耐心等待，保存路径${Path}`);
    }

    async update_GuGuNiu(e) {
        cmd = `git pull`;
        if (this.e.msg.includes('强制'))
            execSync('git fetch && git reset --hard', { cwd: Path });
        exec(cmd, { cwd: Path, stdio: 'inherit' }, (output, error) => {
            if (error) return e.reply(`更新错误：\n${error}`);
            else { e.reply(`更新完成：${output}`); this.apply_GuGuNiu(e); }
        });

        await e.reply(`更新中，耐心等待，保存路径${Path}`);
    }
    async apply_GuGuNiu(e) {
        if (process.platform == 'win32') {
            let _Path = Path.replace(/\//g, '\\');
            cmd = `xcopy ${_Path}* .\\plugins\\miao-plugin\\models\\character /e /y`;
        }
        else
            cmd = `cp -a -f -l ${Path}* ./plugins/miao-plugin/apps/models/character`;
        exec(cmd, { cwd: process.cwd(), stdio: 'inherit' }, (error) => {
            if (error) return e.reply(`应用错误：\n${error}`);
            else e.reply(`应用完成`);
        });

        await e.reply(`应用中`);
        await this.reply(`应用中`);
    }
}
